#! /usr/bin/python
# -*- coding: utf-8 -*-

from google.appengine.ext import db
import utils

#some configuration value
commentMinLen = 3
commentMaxLen = 300

#some Constants
paperCommentStatusNormal = 0
paperCommentStatusDeleted = 1
paperCommentStatusProhibited = 2

#error info definition:
COMMENT_ERROR_CODE_SUCCESS = 0
COMMENT_ERROR_CODE_NOT_LOGGED_IN = 1
COMMENT_ERROR_CODE_LOSE_PARAMS = 2
COMMENT_ERROR_CODE_EMPTY = 3
COMMENT_ERROR_CODE_TOO_SHORT = 4
COMMENT_ERROR_CODE_TOO_LONG = 5
COMMENT_ERROR_CODE_FILTER_FAILED = 6
COMMENT_ERROR_CODE_NO_SUCH_COMMENT = 7
COMMENT_ERROR_CODE_NO_CORRESPONDING_PAPER = 8
COMMENT_ERROR_CODE_NO_DELETE_PERMISSION = 9

COMMENT_ERROR_MESSAGES = [
    '成功',
    '你需要先登录才行:)',
    '缺少重要参数，请联系管理员',
    '评论内容不能为空',
    '评论内容太短，最少' + str(commentMinLen) + '个字',
    '评论内容太长，最多' + str(commentMaxLen) + '个字',
    '评论内容过滤失败',
    '此条评论不存在',
    '找不到此条评论没有对应的文章',
    '你没有删除此条评论的权限'
    ]

class PaperComment(db.Model):
    cid = db.IntegerProperty()
    pid = db.IntegerProperty()
    commenterId = db.IntegerProperty()
    comment = db.StringProperty(multiline=False)
    createdTime = db.DateTimeProperty(auto_now_add=True)
    status = db.IntegerProperty()

def readPaperCommentById(commentId):
    q = db.GqlQuery("SELECT * FROM PaperComment WHERE cid = :cid and status = :status", cid=commentId, status=paperCommentStatusNormal)
    paperCommentModel = q.get()
    if paperCommentModel:
        paperCommentModel.createdTimeInLocalTimezone = utils.calculateLocalTime(paperCommentModel.createdTime)
    return paperCommentModel

def writePaperComment(paperCommentModel):
    paperCommentModel.put()

def listCommentsByPaperId(paperId, offset=0, limit=1000):
    gplQuery = db.GqlQuery("SELECT * FROM PaperComment WHERE pid = :pid and status = :status ORDER BY createdTime ASC", pid=paperId, status=paperCommentStatusNormal)
    resultList = gplQuery.fetch(limit, offset)
    return calculateLocalTimeCommentList(resultList)

def  calculateLocalTimeCommentList(queryResultList):
    for paperCommentModel in queryResultList:
        paperCommentModel.createdTimeInLocalTimezone = utils.calculateLocalTime(paperCommentModel.createdTime)
    return queryResultList

def checkPaperComment(comment):
    if not comment:
        return COMMENT_ERROR_CODE_EMPTY
    if len(comment) < commentMinLen:
        return COMMENT_ERROR_CODE_TOO_SHORT
    if len(comment) > commentMaxLen:
        return COMMENT_ERROR_CODE_TOO_LONG
    
    return COMMENT_ERROR_CODE_SUCCESS